package dev.blogmoon.cn.common.utils;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.google.common.collect.Lists;
import dev.blogmoon.cn.common.entity.PageResult;
import lombok.experimental.UtilityClass;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.function.Function;


@UtilityClass
public class PageUtil {

    public <T, R> PageResult<T> getPage(Page<R> page, Class<T> clazz) {
        PageResult<T> pageResult = new PageResult<T>();
        pageResult.setPageNo((int) page.getCurrent());
        pageResult.setPageSize((int) page.getSize());
        pageResult.setTotalCount((int) page.getTotal());
        pageResult.setTotalPageCount(getTotalPageCount(pageResult.getTotalCount(),pageResult.getPageSize()));
        pageResult.setDataList(BaseConvert.convertList(page.getRecords(), clazz));
        return pageResult;
    }

    public <T, R> PageResult<T> getPage(Page<R> page, Function<R, T> function) {
        PageResult<T> pageResult = new PageResult<T>();
        pageResult.setPageNo((int) page.getCurrent());
        pageResult.setPageSize((int) page.getSize());
        pageResult.setTotalCount((int) page.getTotal());
        pageResult.setTotalPageCount(getTotalPageCount(pageResult.getTotalCount(),pageResult.getPageSize()));
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return pageResult;
        }
        List<T> resultList = Lists.newArrayList();
        for (R data : page.getRecords()) {
            resultList.add(function.apply(data));
        }
        pageResult.setDataList(resultList);
        return pageResult;
    }


    private int getTotalPageCount(int totalCount,int pageSize){
        return totalCount % pageSize >0?totalCount/pageSize +1 : totalCount/pageSize;
    }
}
